<template>
    <ElSelect 
        v-model="selectedValues" 
        filterable 
        clearable 
        multiple 
        v-bind="$attrs" 
        @update:model-value="onInput"
    >
        <ElOption v-for="item in options" :key="item.val" :label="item.name" :value="item.val" />
    </ElSelect>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElSelect, ElOption } from 'element-plus'
import { getDictInfo } from '../api';

interface Props {
    data: any;
    modelValue?: any;  // 添加 modelValue prop 用于 v-model
}

const props = withDefaults(defineProps<Props>(), {
    data: () => ({}),
    modelValue: () => []
})

const emit = defineEmits<{
    'update:model-value': [value: any]
}>()

const options = ref<Array<{ val: string, name: string }>>([])
const selectedValues = ref<any[]>([])

// 初始化从 props.modelValue 或 props.data.gzbqInfo 获取值
watch(() => props.modelValue, (newVal) => {
    selectedValues.value = newVal
}, { immediate: true })

watch(() => props.data.gzbqInfo, (newVal) => {
    if (newVal) {
        try {
            selectedValues.value = JSON.parse(newVal)
            emit('update:model-value', selectedValues.value)
        } catch (e) {
            console.error('解析 gzbqInfo 失败', e)
        }
    }
}, { immediate: true })

const onInput = (value: any) => {
    selectedValues.value = value
    emit('update:model-value', value)
}

const getOptions = () => {
    getDictInfo("gzbq")
        .then(res => {
            options.value = res
        })
}

onMounted(() => {
    getOptions()
})
</script>